package com.peng.commonlibrary.appupdate.usesystemdownload;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

/**
 * Created by M_genius on 2018/1/25 15:04.
 * 描述：用于更新 app 的工具类
 */

public class UpdateAppUtils {

    private final String TAG = "UpdateAppUtils";

    private Activity activity;

    //服务器apk版本
    private int serverVersionCode = 0;
    private String serverVersionName = "";

    //apk存储路径
    private String apkPath = "";

    //当前apk的版本号、版本名称
    private int localVersionCode = 0;
    private String localVersionName = "";

    //下载是否显示通知
    public static boolean showNotification = false;

    private String updateInfo = "";


    /**
     * 在构造方法中获取本地app的版本信息
     * @param activity
     */
    private UpdateAppUtils(Activity activity) {
        this.activity = activity;
        getAPPLocalVersion(activity);
    }

    public static UpdateAppUtils from(Activity activity) {
        return new UpdateAppUtils(activity);
    }


    /**
     * 设置apk的下载路径
     * @param apkPath
     * @return
     */
    public UpdateAppUtils setApkDownloadPath(String apkPath) {
        this.apkPath = apkPath;
        return this;
    }


    public UpdateAppUtils showNotification(boolean showNotification) {
        this.showNotification = showNotification;
        return this;
    }

    /**
     * 设置新版 app 的相关信息
     * @param updateInfo
     * @return
     */
    public UpdateAppUtils setUpdateInfo(String updateInfo) {
        this.updateInfo = updateInfo;
        return this;
    }


    public UpdateAppUtils setServerVersionCode(int serverVersionCode) {
        this.serverVersionCode = serverVersionCode;
        return this;
    }

    public UpdateAppUtils setServerVersionName(String serverVersionName) {
        this.serverVersionName = serverVersionName;
        return this;
    }

    /**
     * 获取 apk 的版本号 currentVersionCode
     */
    private void getAPPLocalVersion(Context ctx) {
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            localVersionName = info.versionName; // 版本名
            localVersionCode = info.versionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新 App ，先判断版本号
     */
    public void update() {
        if (serverVersionCode > localVersionCode) {
            realUpdate();
        }
    }

    /**
     * 判断 app 是否满足更新条件
     *  可以通过版本号、版本名等，在这里只判断了版本号，只要服务器版本号大于本地版本号就进行更新
     * @return
     */
    public boolean isUpdate(){
        if (serverVersionCode > localVersionCode) {
            return true;
        }
        return false;
    }

    private void realUpdate() {
        AppUpdateHintCommonDialog dialog = new AppUpdateHintCommonDialog(activity, new Callback() {
            @Override
            public void callback(int position) {
                if (position == 1) {
                    if (isWifiConnected(activity)) {
                        DownloadAppUtils.getInstance().downloadApk(activity, apkPath, "demo.apk", serverVersionName);
                        //DownloadAppUtils.getInstance().downloadApk(activity, apkPath, "demo.apk", serverVersionName);
                    } else {
                        new AppUpdateHintCommonDialog(activity, new Callback() {
                            @Override
                            public void callback(int position) {
                                if (position == 1) {
                                    DownloadAppUtils.getInstance().downloadApk(activity, apkPath, "demo.apk", serverVersionName);
                                }
                            }
                        }).setContent("目前手机不是WiFi状态\n确认是否继续下载更新？").show();
                    }
                }
            }
        });

        String content = "发现新版本:" + serverVersionName + "\n是否下载更新?";
        if (!TextUtils.isEmpty(updateInfo)) {
            content = "发现新版本:" + serverVersionName + "是否下载更新?\n\n" + updateInfo;
        }
        dialog.setContent(content);
        dialog.setCancelable(false);
        dialog.show();
    }


    /**
     * 检测wifi是否连接
     */
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            }
        }
        return false;
    }

}
